package com.guli.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.guli.common.to.SkuHasStockVo;
import com.guli.common.to.mq.OrderTo;
import com.guli.common.to.mq.StockDetailTo;
import com.guli.common.to.mq.StockLockedTo;
import com.guli.common.utils.R;
import com.guli.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.guli.gulimall.ware.entity.WareOrderTaskEntity;
import com.guli.gulimall.ware.exception.NoStockException;
import com.guli.gulimall.ware.feign.OrderFeignService;
import com.guli.gulimall.ware.feign.ProductFeignService;
import com.guli.gulimall.ware.service.WareOrderTaskDetailService;
import com.guli.gulimall.ware.service.WareOrderTaskService;
import com.guli.gulimall.ware.vo.OrderItemVo;
import com.guli.gulimall.ware.vo.OrderVo;
import com.guli.gulimall.ware.vo.SkuWareHasStock;
import com.guli.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.ware.dao.WareSkuDao;
import com.guli.gulimall.ware.entity.WareSkuEntity;
import com.guli.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * wareId: 123,//仓库id
         *    skuId: 123//商品id
         */
        QueryWrapper<WareSkuEntity> wapper = new QueryWrapper<>();
        String wareId = (String) params.get("wareId");
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(wareId)) {
            wapper.eq("ware_id", wareId);
        }
        if (!StringUtils.isEmpty(skuId)) {
            wapper.eq("sku_id", skuId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wapper
        );

        return new PageUtils(page);
    }

    /**
     * @param skuId  skuid
     * @param wareId 仓库ID
     * @param skuNum 采购数量
     */
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断如果还没有库存记录则新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities == null && wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //远程查询sku的名字,如果失败整个事务不需要回滚
            //1.自己catch 掉
            //2.todo 还可以用什么方法让异常出现以后不会滚？ 高级部分
            try {
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0) {
                    Map<String, Object> object = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) object.get("skuName"));
                }
            } catch (Exception e) {

            }
            wareSkuDao.insert(wareSkuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            //查询当前sku的总库存量
            Long count = this.baseMapper.getSkuStock(skuId);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count == null ? false : count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * rollbackFor = NoStockException.class  回滚设置
     * 默认运行时异常都会回滚
     * <p>
     * 库存解锁的场景
     * 1.下订单成功，订单国企没有制度被系统自动取消、被用户手动取消。都要解锁库存
     * 2.下订单成功，库存成功，接下来的业务调用失败导致订单会回滚。 之前锁定的库存就要解锁
     *
     * @param lockVo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo lockVo) {
        /**
         * 保存库存工作单数据
         * 追溯。
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(lockVo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        //根据商品找到一个仓库，锁定库存
        //1.找到每个商品在哪个仓库有库存
        List<OrderItemVo> locks = lockVo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            Long skuId = item.getSkuId();
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(item.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());
        //2.锁定库存
        Boolean allLock = true; //锁库标志位，默认正常锁定
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;//单个商品锁库标志位，默认商品锁库失败

            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                //没有库存
                throw new NoStockException(skuId);
            }
            //1.如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发送给MQ
            //2、锁定失败，前面保存的工作单信息就会滚了。发送出去的消息即使要解锁记录，由于查不到id，所以就不用解锁
            //3. 1.  1(商品)-2（仓库）-1（件） 2.  2-1-2   3.  3-1-1
            for (Long wareId : wareIds) {
                //成功就返回1，否则就是0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    //锁定成功
                    skuStocked = true;
                    /**
                     *锁定成功保存库存工作单详情
                     * 追溯
                     */
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, null, hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(taskDetailEntity);
                    //todo 告诉MQ锁定成功
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, stockDetailTo);
                    //工作单详情数据 mq
                    stockLockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                }
            }
            if (!skuStocked) {
                //当前商品锁库失败
                throw new NoStockException(skuId);
            }
        }

        //程序运行到这，锁库成功
        return true;
    }

    @Override
    public void unLockStock(StockLockedTo to) {
        Long id = to.getId();//库存工作单的id
        StockDetailTo detail = to.getDetail();
        Long skuId = detail.getSkuId();
        //库存工作单详情id
        Long detailId = detail.getId();

        /**
         *1.查询数据库这个订单的锁定库存信息
         * 有:证明库存锁定成功，解锁要看订单的情况
         *    解锁：看订单情况
         *    1.没有这个订单，必须解锁
         *    2.有这个订单。看订单状态
         *      订单状态：已取消：解锁库存；没取消：不能解锁
         *没有：库存锁定失败了，库存回滚了。这种情况无需解锁
         *解锁失败，一定要告诉mq不要删除消息，设置手动档ack
         */
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if (byId != null) {
            WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(id);
            String orderSn = orderTaskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderVo order = r.getData(new TypeReference<OrderVo>() {
                });
                if (order == null || order.getStatus() == 4) {
                    //无订单或者订单状态为已取消，解锁
                    if(byId.getLockStatus() == 1){
                        //当前库存工作单未解锁，才解锁
                        unLockStock(skuId, detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                throw new RuntimeException("远程服务失败");
            }
        } else {
            //无需解锁
        }
    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存消息优先到期。查订单状态肯定是新建状态，什么都做不了。
     * 导致库存永远不会解锁。
     * 订单失效之后在发一条消息解锁库存。双重保障
     *
     * @param order
     */
    @Transactional
    @Override
    public void unLockStock(OrderTo order) {
        String orderSn = order.getOrderSn();
        //查一下最新的库存解锁状态，防止重复解锁
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        //按照工作单找到所有没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> detail_task = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status",1));
        if(detail_task != null && detail_task.size() > 0){
            for (WareOrderTaskDetailEntity entity : detail_task) {
                //Long skuId, Long wareId, Integer num, Long taskDeatilId
                unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
            }
        }
    }

    /**
     * 解锁库存
     *
     * @param skuId        商品id
     * @param wareId       仓库id
     * @param num          几件
     * @param taskDeatilId 库存工作单id
     */
    public void unLockStock(Long skuId, Long wareId, Integer num, Long taskDeatilId) {
        //库存解锁
        wareSkuDao.unLockStock(skuId, wareId, num);
        //更新库存工作单的解锁状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDeatilId);
        entity.setLockStatus(2);//变为解锁
        wareOrderTaskDetailService.updateById(entity);

    }

    //商品在哪些仓库有货
//    @Data
//    class SkuWareHasStock {
//        public SkuWareHasStock(){
//        }
//        private Long skuId;
//        private List<Long> wareId;
//        private Integer num;
//    }

}